<?php
/**
 * Created by PhpStorm.
 * User: Argon
 * Date: 2016/12/14
 * Time: 15:35
 */

namespace Admin\Model;

use Org\Util\String;
use Think\Model;
use Think\Page;

class AdminModel extends Model
{
    protected $patchValidate = true;
    //array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间]),
    protected $_validate = array(
        ['name', 'require', '管理员名称不能为空'],
        ['name', '', '管理员名称已被占用', self::EXISTS_VALIDATE, 'unique', 'add'],
        ['password', 'require', '密码不能为空'],
        ['repassword', 'password', '两次密码不一致', self::EXISTS_VALIDATE, 'confirm'],
        ['is_show', ['1','0'], '状态错误', self::EXISTS_VALIDATE, 'in'],
        ['sort', ['1','5'], '排序必须在1-5之间', self::EXISTS_VALIDATE, 'between'],
    );
    //array(完成字段2,完成规则,[完成条件,附加规则]),
    protected $_auto = array(
        array('salt','getSalt','add','callback'),
        array('password','md5','add','function'),
        array('password','md5','chpwd','function'),
        array('create_time','time','add','function'),
        array('login_ip','getIp','login','callback'),
    );

    public function getSalt(){
        return String::randString(6);
    }
    public function getIp(){
        return ip2long(get_client_ip());
    }

    public function addAdmin(){
        $this->data['create_time']=date("Y-m-d H:i:s",$this->data['create_time']);
        $this->data['password']=md5($this->data['password'].$this->data['salt']);
        return $this->add();
    }

    public function getPageData(array $cond=[]){
        $cond = array_merge(['is_show'=>['neq',-1]],$cond);
        $count = $this->where($cond)->count();
        $page = new Page($count, C('PAGE.SIZE'));
        $page->setConfig('theme', C('PAGE.THEME'));
        $page_html = $page->show();
        $rows = $this->where($cond)->page(I('get.p'),C('PAGE.SIZE'))->order('sort asc')->select();
        //返回数据
        return [
            'page_html'=>$page_html,
            'rows'=>$rows,
        ];
    }

}